<!--  -->
<template>
  <a-modal
    width="80%"
    :title="titles[openType]"
    :visible="innerVisible"
    @cancel="handleCancel"
    :footer="null"
  >
    <!-- 查看研究中心 -->
    <template v-if="openType === 1">
      <a-descriptions :title="$t('all.autotext1403')" bordered>
        <a-descriptions-item :label="$t('all.autotext1364')">{{ formData.researchCenterNo }}</a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext1368')">{{ formData.orgName }}</a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext744')">{{ formData.enName }}</a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext60')">{{ formData.active | enumValueByKey($const.RESEARCH_CENTER_STATUS) }}</a-descriptions-item>
      </a-descriptions>
    </template>
    <!-- 编辑研究中心 -->
    <template v-else>
      <a-descriptions :title="$t('all.autotext1403')"></a-descriptions>
      <a-form-model
        :model="formData"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="formRules"
        ref="formRef"
      >
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item :label="$t('all.autotext1364')" prop="researchCenterNo">
              <a-input v-model="formData.researchCenterNo" :placeholder="$t('all.autotext1127')"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item :label="$t('all.autotext1368')" prop="orgId">
              <a-select @change="handleHospitalSelect" v-model="formData.orgId" :disabled="openType === 2">
                <a-select-option v-for="item in hospitalList" :key="item.id" :value="item.id">
                  {{ item.orgName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item :label="$t('all.autotext744')">
              <a-input v-model="formData.enName" :placeholder="$t('all.autotext781')"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <!-- epv2.0 版本 中心状态调整变为列表操作列新增入口，不再在弹窗中编辑 -->
          <!--<a-col :span="8">-->
          <!--  <a-form-model-item label="中心状态">-->
          <!--    <a-select v-model="formData.active" allowClear>-->
          <!--      <a-select-option v-for="item in $const.RESEARCH_CENTER_STATUS" :key="item.value" :value="item.value">{{ item.desc }}</a-select-option>-->
          <!--    </a-select>-->
          <!--  </a-form-model-item>-->
          <!--</a-col>-->
          <!-- <a-col :span="8">
            <a-form-model-item label="中心研究者">
              <a-select
                mode="multiple"
                :maxTagCount="2"
                placeholder="请先选择中心研究者"
                v-model="formData.teamIdPi"
                :filter-option="filterOption"
                @change="handlePIChange"
              >
                <a-select-option v-for="item in teamPIList" :key="item.id" :value="item.id">
                  {{ item.account }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="中心CRC">
              <a-select
                mode="multiple"
                :maxTagCount="2"
                placeholder="请先选择中心CRC"
                v-model="formData.teamIdP"
                :filter-option="filterOption"
                allowClear
              >
                <a-select-option v-for="item in teamCrcList" :key="item.id" :value="item.id">
                  {{ item.account }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="中心CRA">
              <a-select
                mode="multiple"
                :maxTagCount="2"
                placeholder="请先选择中心CRA"
                v-model="formData.teamIdCraP"
                :filter-option="filterOption"
                allowClear
              >
                <a-select-option v-for="item in teamCraList" :key="item.id" :value="item.id">
                  {{ item.account }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </a-form-model>
    </template>

    <div class="dialog-footer" v-if="openType !== 1">
      <a-button @click="handleCancel" style="margin-right: 20px;">{{ $t('all.autotext975') }}</a-button>
      <a-button type="primary" :loading="loading" @click="clickSaveCenter">{{ $t('all.autotext49') }}</a-button>
    </div>
  </a-modal>
</template>

<script>
import { getCenterDetail, updateCenter, getListCrc, getListCra, addCenter, getListPI } from '@/api/project/configItem/member'
import { getOriginationList, listOrgDepts } from '@/api/common'
import modalMixin from '@/utils/modal.mixin'
import cloneDeep from 'lodash.clonedeep'

export default {
  props: ['openType', 'centerId', 'configId'],
  mixins: [modalMixin],
  data () {
    return {
      proId: '',
      titles: [this.$t('all.autotext462.1'), this.$t('all.autotext462.2'), this.$t('all.autotext462.3')],
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      formData: {
        proId: null,
        orgId: null,
        active: null,
        enName: '',
        shortName: '',
        teamIdPi: [],
        teamIdP: [],
        teamIdCraP: [],
        researchCenterNo: null,
        orgDeptId: []
      },
      formRules: {
        orgId: [{ required: true, message: this.$t('all.autotext77'), trigger: 'change' }],
        researchCenterNo: [
          { required: true, message: this.$t('all.autotext1127'), trigger: 'change' },
          { pattern: /^[0-9a-zA-Z-_]{1,}$/, message: this.$t('all.autotext1400') }
        ]
      },
      hospitalList: [],
      departmentList: [],
      teamPIList: [],
      teamCrcList: [],
      teamCraList: [],
      submitting: false,
      beforeData: {},
      loading: false
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.proId = parseInt(pd)
    }
  },
  methods: {
    modalUpdated () {
      this.openType > 0 && this.getCenterDetail()
      this.getHospitalList()
      // this.getListPI()
      // this.getListCrc()
      // this.getListCra()
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取中心研究者列表
    getListPI () {
      getListPI({ proId: this.proId, configId: this.configId }).then(res => {
        this.teamPIList = res
      })
    },
    // 获取crc列表
    async getListCrc () {
      this.teamCrcList = await getListCrc({ proId: this.proId, configId: this.configId })
    },
    // 获取cra列表
    async getListCra () {
      this.teamCraList = await getListCra({ proId: this.proId, configId: this.configId })
    },
    // 获取中心详情
    async getCenterDetail () {
      const res = await getCenterDetail({ resId: this.centerId, configId: this.configId })
      this.beforeData = cloneDeep(res)
      this.formData = {
        ...res,
        teamIdCraP: res.teamIdCraP ? res.teamIdCraP.split(',').map(Number) : [],
        teamIdP: res.teamIdP ? res.teamIdP.split(',').map(Number) : [],
        orgDeptId: res.orgDeptId ? res.orgDeptId.split(',').map(Number) : [],
        teamIdPi: res.teamIdPi ? res.teamIdPi.split(',').map(Number) : []
      }
      this.listOrgDepts(res.orgId)
    },
    // 请求医院列表
    async getHospitalList () {
      const res = await getOriginationList()
      this.hospitalList = res.filter(item => parseInt(item.type) === 2) // 获取的列表中type值为2的是医院
    },
    // 请求科室列表
    async listOrgDepts (val) {
      this.departmentList = await listOrgDepts({ orgId: val })
    },
    // 医院选择下拉改变
    handleHospitalSelect (val) {
      if (val) {
        this.listOrgDepts(val)
      } else {
        this.formData.enName = ''
        this.formData.shortName = ''
        this.departmentList = []
      }

      this.formData.orgDeptId = [] // 将此前选的科室清空
    },
    handlePIChange (value) {
      this.formData.teamIdPi = value
    },
    // 点击保存研究中心
    clickSaveCenter () {
      this.$refs.formRef.validate(valid => {
        if (!valid) {
          this.$message.error(this.$t('all.autotext847'))
          return false
        }
        this.loading = true
        const { id, researchCenterNo, orgId, enName, shortName, active, proId, orgDeptId, teamIdP, teamIdCraP, teamIdPi } = { ...this.formData }
        const commitData = { id, researchCenterNo, orgId, enName, shortName, active, proId, orgDeptId, teamIdP, teamIdCraP, teamIdPi }
        commitData.orgDeptName = this.departmentList.filter(item => commitData.orgDeptId.indexOf(item.id) >= 0).map(item => item.name).join()
        commitData.orgDeptId = commitData.orgDeptId ? commitData.orgDeptId.toString() : ''
        commitData.teamIdP = commitData.teamIdP ? commitData.teamIdP.toString() : ''
        commitData.teamIdCraP = commitData.teamIdCraP ? commitData.teamIdCraP.toString() : ''
        commitData.proId = this.$store.getters.project.id
        commitData.teamIdPi = commitData.teamIdPi ? commitData.teamIdPi.toString() : ''
        // 日志数据处理
        commitData.orgName = this.hospitalList.find(item => Number(item.id) === Number(this.formData.orgId)).orgName
        commitData.craAccount = commitData.teamIdCraP ? commitData.teamIdCraP.split(',').map(val => this.teamCraList.find(item => Number(item.id) === Number(val)).account).join(',') : ''
        commitData.crcAccount = commitData.teamIdP ? commitData.teamIdP.split(',').map(val => this.teamCrcList.find(item => Number(item.id) === Number(val)).account).join(',') : ''
        commitData.activeDesc = commitData.active ? commitData.active === 1 ? '活跃' : '非活跃' : ''
        this.beforeData.craAccount = this.beforeData.teamIdCraP ? this.beforeData.teamIdCraP.split(',').map(val => this.teamCraList.find(item => Number(item.id) === Number(val)).account).join(',') : ''
        this.beforeData.crcAccount = this.beforeData.teamIdP ? this.beforeData.teamIdP.split(',').map(val => this.teamCrcList.find(item => Number(item.id) === Number(val)).account).join(',') : ''
        commitData.beforeData = JSON.stringify(this.beforeData)
        commitData.configId = this.configId

        this.submitting = true
        // 若未选活跃状态 则解构时将active字段过滤了 故需补上
        if (!commitData.active) commitData.active = ''
        const action = this.openType === 0 ? addCenter : updateCenter
        action({ ...commitData })
          .then(res => {
            this.loading = false
            this.submitting = false
            this.$message.success(this.$t('all.autotext470'))
            this.$emit('refresh')
            this.handleCancel()
          })
          .catch(() => {
            this.loading = false
            this.submitting = false
          })
      })
    },
    handleCancel () {
      this.innerVisible = false
      this.resetForm()
    },
    resetForm () {
      this.$refs.formRef && this.$refs.formRef.resetFields()
      this.hospitalListView = []
      this.crcListView = []
      this.piListView = []
      this.craListView = []
      this.formData = {
        proId: null,
        orgId: null,
        active: null,
        enName: '',
        shortName: '',
        teamIdPi: [],
        teamIdP: [],
        teamIdCraP: [],
        researchCenterNo: null,
        orgDeptId: []
      }
    }
  }
}
</script>
<style scoped lang="less">
.title {
  line-height: 32px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: bold;
  font-size: 16px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
